package org.abettor.nookinfo.novel;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.abettor.nookinfo.AddressConstant;
import org.abettor.nookinfo.R;
import org.abettor.nookinfo.ads.YoumiManager;
import org.abettor.nookinfo.modal.Pair;
import org.abettor.nookinfo.persist.NovelHelper;
import org.abettor.nookinfo.service.NovelDownloadService;
import org.abettor.nookinfo.service.NovelDownloadService.NovelDownloadBinder;
import org.abettor.nookinfo.view.OnPageJumpListener;
import org.abettor.nookinfo.view.PageDialog;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.LinearLayout.LayoutParams;

/**
 * 文章段落类
 * @author abettor
 *
 */
public class NovelChapter extends Activity
{
	public static final String NOVEL_ID = "NOVEL_ID";
	public static final String NOVEL_NAME = "NOVEL_NAME";
	private static final int REFRESHED = 1;//文章更新已完成事件
	private static final int FAILED = 2;//文章更新失败时间
	private static final int MENU_PREV = Menu.FIRST + 1;
	private static final int MENU_NEXT = MENU_PREV + 1;
	private static final int MENU_JUMP = MENU_NEXT + 1;
	private static final int MENU_REFRESH = MENU_JUMP + 1;
	private static final int MENU_DOWNLOAD = MENU_REFRESH + 1;
	private static final int MENU_CLOSE = MENU_DOWNLOAD + 1;
	private YoumiManager youmi = new YoumiManager(this);
	private int novel;
	private String novelName;
	private String novelCategoryName;
	private int total = -1;
	private int page = 1;
	private List<Pair<String, Integer>> chapterList = new ArrayList<Pair<String, Integer>>();
	private ProgressDialog progressDialog = null;//进度条对话框
	private Worker worker = null;//网络访问线程
	private Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			if(msg.what == REFRESHED)
			{
				LinearLayout layout = (LinearLayout) findViewById(R.id.novelChapterLayout);
				layout.removeAllViews();
				LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				for(Pair<String, Integer> pair : chapterList)
				{
					final Pair<String, Integer> thePair = pair;
					Button btn = new Button(NovelChapter.this);
					btn.setText(thePair.first);
					btn.setBackgroundResource(R.drawable.novel_chapter_button);
					btn.setLayoutParams(params);
					//	设置按钮事件
					btn.setOnClickListener(new OnClickListener()
					{
						@Override
						public void onClick(View view)
						{
							//	打开相应的文章内容
							Bundle extras = new Bundle();
							extras.putString(NovelChapter.NOVEL_NAME, novelName);
							extras.putString(NovelList.NOVEL_CATEGORY_NAME, novelCategoryName);
							extras.putInt(NovelContent.NOVEL_CONTENT_ID, thePair.second);
							Intent novelIntent = new Intent();
							novelIntent.setClass(NovelChapter.this, NovelContent.class);
							novelIntent.putExtras(extras);
							startActivity(novelIntent);
						}
					});
					layout.addView(btn);
				}
				ScrollView scroll = (ScrollView) findViewById(R.id.novelChapterScroll);
				scroll.scrollTo(0, 0);

				//	按照一定的概率显示广告
				Random rand = new Random(System.currentTimeMillis());
				int val = rand.nextInt(99);
				if(val < 20)
				{
					youmi.showYoumi(YoumiManager.Position.bottom, Color.WHITE, Color.BLACK, 0xAA);
				}
			}
			else if(msg.what == FAILED)
			{
				Builder builder = new Builder(NovelChapter.this);
				builder.setTitle(R.string.novel_chapter_fail_title);
				builder.setMessage(R.string.novel_chapter_fail_content);
				builder.setPositiveButton(R.string.novel_chapter_fail_btn_ok, new DialogInterface.OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialoginterface, int i)
					{
						dialoginterface.dismiss();
					}
				});
				builder.show();
			}
			super.handleMessage(msg);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.novel_chapter);
		String label = getString(R.string.novel_chapter_label);
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		novel = extras.getInt(NOVEL_ID);
		novelName = extras.getString(NOVEL_NAME);
		novelCategoryName = extras.getString(NovelList.NOVEL_CATEGORY_NAME);
		label = label.replace("REPL_CATE", novelCategoryName).replace("REPL_NAME", novelName);
		setTitle(label);
		onRefreshClicked(null);
	}

	/**
	 * 创建Menu菜单
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		boolean result = super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_PREV, MENU_PREV, getString(R.string.global_menu_prev)).setIcon(R.drawable.global_menu_prev);
		menu.add(0, MENU_NEXT, MENU_NEXT, getString(R.string.global_menu_next)).setIcon(R.drawable.global_menu_next);
		menu.add(0, MENU_JUMP, MENU_JUMP, getString(R.string.global_menu_jump)).setIcon(R.drawable.global_menu_jump);
		menu.add(0, MENU_REFRESH, MENU_REFRESH, getString(R.string.global_menu_refresh)).setIcon(R.drawable.global_menu_refresh);
		menu.add(0, MENU_DOWNLOAD, MENU_DOWNLOAD, getString(R.string.global_menu_download)).setIcon(R.drawable.global_menu_download);
		menu.add(0, MENU_CLOSE, MENU_CLOSE, getString(R.string.global_menu_close)).setIcon(R.drawable.global_menu_close);

		return result;
	}

	/**
	 * 处理菜单事件
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch(item.getItemId())
		{
		case MENU_PREV:
			onPrevClicked(null);
			break;
		case MENU_NEXT:
			onNextClicked(null);
			break;
		case MENU_JUMP:
			//	跳转到……
			PageDialog pageDialog = new PageDialog(this, total, page);
			pageDialog.setTitle(R.string.global_menu_jump);
			pageDialog.setOnPageJumpListener(new OnPageJumpListener()
			{
				@Override
				public void onPageJump(PageDialog dialog)
				{
					int current = dialog.getCurrentPage();
					if(current <= 0 || current > total)
					{
						return;
					}

					page = current;
					dialog.dismiss();
					onRefreshClicked(null);
				}
			});
			pageDialog.show();
			break;
		case MENU_DOWNLOAD:
			{
				final ServiceConnection sc = new ServiceConnection()
				{
					@Override
					public void onServiceDisconnected(ComponentName name)
					{
					}
	
					@Override
					public void onServiceConnected(ComponentName name, IBinder service)
					{
						NovelDownloadBinder binder = (NovelDownloadBinder) service;
						NovelDownloadService serv = binder.getService();
						serv.download(novel, novelName);
						unbindService(this);
					}
				};
				final Intent intent = new Intent();
				intent.setClass(this, NovelDownloadService.class);

				NovelHelper helper = new NovelHelper(this);
				if(helper.getLocalNovel(novel) != null)
				{
					//	发现文章已存在，提示是否覆盖
					String content = getString(R.string.novel_chapter_download_exist_content).replace("REPL", novelName);
					Builder builder = new Builder(this);
					builder.setTitle(R.string.novel_chapter_download_exist_title);
					builder.setMessage(content);
					builder.setPositiveButton(R.string.novel_chapter_download_exist_btn_ok, new DialogInterface.OnClickListener()
					{
						@Override
						public void onClick(DialogInterface dialog, int which)
						{
							//	创建下载服务，并以回调的方式另其将文章下载到本地
							bindService(intent, sc, BIND_AUTO_CREATE);
							dialog.dismiss();
						}
					});
					builder.setNegativeButton(R.string.novel_chapter_download_exist_btn_cancel, new DialogInterface.OnClickListener()
					{
						@Override
						public void onClick(DialogInterface dialog, int which)
						{
							dialog.dismiss();
						}
					});
					builder.show();
				}
				else
				{
					//	直接创建下载服务，并以回调的方式另其将文章下载到本地
					bindService(intent, sc, BIND_AUTO_CREATE);
				}
			}
			break;
		case MENU_REFRESH:
			onRefreshClicked(null);
			break;
		case MENU_CLOSE:
			onRetrunClicked(null);
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	/**
	 * “刷新”按钮事件方法
	 * @param v
	 */
	public void onRefreshClicked(View v)
	{
		//	刷新段落列表
		chapterList.clear();
		worker = new Worker();
		worker.start();
		progressDialog = new ProgressDialog(this);
		progressDialog.setCancelable(true);
		progressDialog.setTitle(R.string.novel_chapter_progress_title);
		progressDialog.setMessage(getText(R.string.novel_chapter_progress_content));
		progressDialog.setButton(getText(R.string.novel_chapter_progress_btn_cancel), new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialoginterface, int i)
			{
				worker.kill();
			}
		});
		progressDialog.show();
		synchronized (worker)
		{
			worker.notify();
		}
	}

	/**
	 * “返回”按钮事件方法
	 * @param v
	 */
	public void onRetrunClicked(View v)
	{
		finish();
	}

	/**
	 * “上一页”按钮事件方法
	 * @param v
	 */
	public void onPrevClicked(View v)
	{
		if(page <= 1)
		{
			return;
		}

		page --;
		onRefreshClicked(v);
	}

	/**
	 * “下一页”按钮事件方法
	 * @param v
	 */
	public void onNextClicked(View v)
	{
		page ++;
		onRefreshClicked(v);
	}

	/**
	 * 读取文章章节列表的工作线程类
	 * @author abettor
	 *
	 */
	private class Worker extends Thread
	{
		//	线程是否为意外退出的标记
		private boolean cancel = false;

		/**
		 * 强制杀死工作者线程
		 */
		public void kill()
		{
			cancel = true;
			this.interrupt();
		}

		@Override
		public void run()
		{
			try
			{
				//	等待对话框创建完成
				synchronized (this)
				{
					wait();
				}

				//	此处访问网络并获取文章章节列表
				fetchChapters(chapterList);

				//	关闭进度对话框并通知界面更新
				progressDialog.dismiss();
				if(! cancel)
				{
					//	在非意外中断情况下才更新界面
					Message msg = new Message();
					msg.what = REFRESHED;
					handler.sendMessage(msg);
				}
				else
				{
					//	意外中断的情况下，显示错误对话框
					Message msg = new Message();
					msg.what = FAILED;
					handler.sendMessage(msg);
				}
			}
			catch (Exception e)
			{
				//	清除按钮列表
				try { progressDialog.dismiss(); } catch (Exception ex) { };
				chapterList.clear();
				//	意外中断的情况下，显示错误对话框
				Message msg = new Message();
				msg.what = FAILED;
				handler.sendMessage(msg);
				Log.d(this.getClass().getName(), "", e);
			}
		}

		//	读取文章章节列表
		private void fetchChapters(List<Pair<String, Integer>> chapterList) throws Exception
		{
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			String url = AddressConstant.NOVEL_CHAPTER.replace("ID", novel + "").replace("PAGE", page + "");
			Document doc = db.parse(url);
			NodeList list = doc.getElementsByTagName("chapter");
			int len = list.getLength();
			for(int i = 0; i < len; i ++)
			{
				Pair<String, Integer> pair = new Pair<String, Integer>();
				Node node = list.item(i);
				NodeList nodes = node.getChildNodes();
				int count = nodes.getLength();
				for(int j = 0; j < count; j ++)
				{
					Node pairNode = nodes.item(j);
					String nodeName = pairNode.getNodeName();
					if("id".equals(nodeName))
					{
						String id = pairNode.getTextContent();
						pair.second = Integer.valueOf(id);
					}
					else if("name".equals(nodeName))
					{
						String name = pairNode.getTextContent();
						pair.first = name;
					}
				}
				if(pair.first != null && pair.second != null)
				{
					chapterList.add(pair);
				}
			}

			list = doc.getElementsByTagName("page");
			String pageNo = list.item(0).getTextContent();
			page = Integer.parseInt(pageNo);

			list = doc.getElementsByTagName("total");
			if(list != null && list.getLength() > 0)
			{
				String totalPage = list.item(0).getTextContent();
				total = Integer.parseInt(totalPage);
			}
		}
	}
}
